<div class="container-fluid" id="tableSpl">
	<h4 class="c-grey-900 mT-10 mB-30" th:text="#{spl.admin.title}"></h4>
	<div class="row" id="spl-panel">
		<div class="col-md-12">
			<div class="bgc-white bd bdrs-3 p-20 mB-20">
				<h4 class="c-grey-900 mB-20" th:text="#{table.spl.title}"></h4>
				<table id="splTable" class="table table-striped table-bordered" 
					cellspacing="0" width="100%">
					<thead>
						<tr>
							<!-- Columna oculta para el identificador de la plataforma -->
							<th></th>
							<th th:text="#{table.spl.name}"></th>
							<th th:text="#{table.spl.description}"></th>
							<th th:text="#{table.spl.type}"></th>
							<th th:text="#{table.spl.url}"></th>
							<th th:text="#{table.spl.key}"></th>
					
						</tr>
					</thead>
				</table>
			</div>
		</div>
	</div>
</div>

<script th:inline="javascript">
$(document).ready(function() {
				
	var actionSave = /*[[@{/savespl}]]*/;
	var actionDelete = /*[[@{/deletespl}]]*/;
	var getSpls = /*[[@{/spldatatable}]]*/;
	var editTemplate = /*[[@{/editspl}]]*/;
	var addTemplate = /*[[@{/addspl}]]*/;
	
	var tbl = $('#splTable').DataTable({
		dom: 'Bfrtip',
	    select: 'single',
	    responsive: true,

	    altEditor: true,
	    buttons: [
	    	{text: 'Conectar', name: 'connect', extend: 'selected', action: connectToSpl},
	    	{text: 'Agregar', name: 'add'},
	    	{text: 'Editar', name: 'edit', extend: 'selected'},
	    	{text: 'Eliminar', name: 'delete', extend: 'selected'}
	    ],

	    "iTotalRecords": "totalElements",
        "iTotalDisplayRecords": "numberOfElements",

		"processing": true,
	    "serverSide": true,
		"ajax": {
	        "url": getSpls,
	        "dataSrc" : "data",
	        "data": function (data) {
	        	// Datos a pasar al modal
	            data.formId = "splForm";
	            data.editTemplate = editTemplate;
	            data.addTemplate = addTemplate;
	        }
	    },
	    "language": {
	        "url": "js/datatables/i18n/spanish.json",
	        select: {
	            rows: {
	                _: "%d filas seleccionadas",
	                1: "1 fila seleccionada"
	            }
	          }
	        },
		"columns": [
	        { "data": "idSpl", "visible": false},
	        { "data": "name" },
	        { "data": "description", "visible": false },
	        { "data": "type" },
	        { "data": "url" },
	        { "data": "key", "visible": false },
	    
	        ]
		}).on('crudaction', function(e, accion, idSpl, data, rowindex){
		    // e          Evento Jquery
		    // accion     [add|edit|delete]
		    // pkid       Primer campo en la data [id]                ... en add,    retorna null
		    // data       Los campos adicionales  [campo_1, campo_n]  ... en delete, retorna null
		    // rowindex   El index de la fila para el dataTable       ... en add,    retorna null
		    
		    $('#altEditor-modal .modal-body .alert').remove();
		    // Se muestra la capa 'cargando...'
		    loading();
		    
		    switch(accion){
		        case 'add':
		        	if ($('#splForm')[0].checkValidity() === false) {
		        		// Se oculta la capa 'cargando...'
		        		hide();
		                event.stopPropagation();
		                
		                $('#splForm *').filter(':input').each(function(){
		            	    		            	    
		            	    if(!$(this).checkValidity())
		            	    {
		            	  	 $("#invalid-" + $(this).attr('id')).html();
		            	  	 $("#" + $(this).attr('id')).addClass("is-invalid");
		            	    } else {
		            	  	 $("#" + $(this).attr('id')).removeClass("is-invalid");
		            	    }
		            	    
		            	});
		                
		                // Esto es necesario para forzar que se muestren mensajes de validacion de cliente
		                $('<input type="submit">').hide().appendTo($('#splForm')).click().remove();
		            } else {
		            	$.ajax(actionSave, {
			            	dataType : 'json',
			            	contentType:'application/json',
			                data : JSON.stringify(data),
			                type:'POST',
			                success: function(data){
			                  
								var errores = JSON.parse(data.error);
								
								if (data.error != null){
									  jQuery.each(errores, function(i, val) {
										$('#splForm *').filter('.invalid-modal').each(function(){

											if (i == $(this).attr('id')){
												$("#" + i).text(val);
											}
										});
									  });
								} else {
									tbl.row.add($(data.data)).draw(false);
									
									$('#altEditor-modal .modal-body .alert').remove();
				                    $('#altEditor-modal').modal('hide');
								}
			                	
			            		// Se oculta la capa 'cargando...'
			            		hide();
			                    
			                    if ($('#errorModalSpl').length > 0){
									$('#errorModalSpl').remove();
								}
			                    
			                },
			                error:function(data){
			                	hide();
			                	$('#splForm').append('<div id="errorModalSpl" class="alert alert-danger" role="alert"><strong>' + [[#{spl.admin.error.sameValues}]] + '</strong></div>');
			                }
			            });
		            }
		        	$('#splForm').addClass('was-validated');
		            break;
		        case 'edit':
		        	if ($('#splForm')[0].checkValidity() === false) {
		        		// Se oculta la capa 'cargando...'
		        		hide();
		                event.stopPropagation();

		                $('#splForm *').filter(':input').each(function(){

		            	    if(!$(this).checkValidity())
		            	    {
		            	  	 $("#invalid-" + $(this).attr('id')).html();
		            	  	 $("#" + $(this).attr('id')).addClass("is-invalid");
		            	    } else {
		            	  	 $("#" + $(this).attr('id')).removeClass("is-invalid");
		            	    }
		            	    
		            	});
		                
		                // Esto es necesario para forzar que se muestren mensajes de validación de cliente
		                $('<input type="submit">').hide().appendTo($('#splForm')).click().remove();
		            } else {
		            	$.ajax(actionSave, {
			            	dataType : 'json',
			            	contentType:'application/json',
			                data : JSON.stringify(data),
			                type:'POST',
			                success: function(data){
			                  
			            		// Se oculta la capa 'cargando...'
			            		hide();
			                    tbl.row.add($(data.data)).draw(false);
			                    		                    
			                    $('#altEditor-modal .modal-body .alert').remove();
			                    $('#altEditor-modal').modal('hide');
			                    
			                    if ($('#errorModalSpl').length > 0) {
									$('#errorModalSpl').remove();
								}
			                },
			                error:function(data){
			                	hide();
			                	$('#splForm').append('<div id="errorModalSpl" class="alert alert-danger" role="alert"><strong>' + [[#{spl.admin.error.sameValues}]] + '</strong></div>');
			                }
			            });
		            }
		        	$('#splForm').addClass('was-validated');
	            	break;
		        case 'delete':
		            $.ajax(actionDelete,{
		            	data:$.param({'id':idSpl, 'index':rowindex}),
		                type:'POST',
		                success: function(data){
		                    
		                	if (data == "-1" && $('#errorSpl').length == 0){
		                		$('#spl-panel').before('<div id="errorSpl" class="alert alert-danger" role="alert"><strong>' + [[#{spl.admin.error.inUse}]] + '</strong></div>');
		                	}else{
								$('#errorSpl').remove();
							}
		                	
		                	// Se oculta la capa 'cargando...'
		                	hide();
		                    tbl.row(data.index).remove().draw();
		                    
		                    $('#altEditor-modal .modal-body .alert').remove();
		                    $('#altEditor-modal').modal('hide');
		                },
		                error:function(){}
		            });
		            break;
		        default:
		            $('#altEditor-modal .modal-body .alert').remove();
		            $('#altEditor-modal .modal-body').append('<div class="alert alert-danger" role="alert"><strong>' + [[#{alarm.admin.error.NotAuthorized}]] + '</strong></div>');
		            break;
		    }
		});
});

function connectToSpl( e, dt, node, config ) {
	
	e.preventDefault();
	
	// Mostramos dialogo de espera
	loading();
	
	var selectedRows = dt.rows( {selected : true} );
	var rowIndex = selectedRows.indexes()[0]; 
	var splData = selectedRows.data()[0];
	
	var actionConnectSpl = /*[[@{/connectspl}]]*/;
	
	$.ajax(actionConnectSpl, {
    	data : $.param({ 'id' : splData.idSpl, 'name' : splData.name, 'type' : splData.type, 'desc' : splData.description, 'index' : rowIndex}),
        type : 'POST',
        success : function(data){
       	
        	// Se oculta la capa 'cargando...'
			hide();            

        	// Cargamos en el fragmento HTML resultante sustituyendo al actual por medio del componente padre
        	// del elemento principal
			$("#tableSpl").parent().html(data);
        },
        error : function(){
       	
        	// Se oculta la capa 'cargando...'
        	hide();
      	
        	if ($('#errorSpl').length == 0) {
				$('#spl-panel').before('<div id="errorSpl" class="alert alert-danger" role="alert"><strong>' + [[#{spl.admin.error.connecting}]] + '</strong></div>');
        	}
        	else {
        		$('#errorSpl').html('<strong>' + [[#{spl.admin.error.connecting}]] + '</strong>')
        	}
        }
    });
}

</script>